package com.lagou.handler;

import com.lagou.rpc.ApplicationContextUtil;
import com.lagou.rpc.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class ServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        Class<?> clazz = Class.forName(request.getClassName());
        Object bean = ApplicationContextUtil.getBean(clazz);
        Method declaredMethod = clazz.getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
        Object result = declaredMethod.invoke(bean, request.getParameters());
        ctx.writeAndFlush(result);
    }

}